/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: AllOrdersActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import io.bhex.app.R;
import io.bhex.app.account.presenter.AllOrderPresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.event.OrderFilterEvent;
import io.bhex.app.event.RevokeOrderEvent;
import io.bhex.app.skin.view.SkinTabLayout;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.KeyBoardUtil;
import io.bhex.app.view.TopBar;

/**
 * ================================================
 * 描   述：全部订单
 * ================================================
 */

public class AllOrdersActivity extends BaseActivity<AllOrderPresenter, AllOrderPresenter.AllOrderUI> implements AllOrderPresenter.AllOrderUI, View.OnClickListener, ViewPager.OnPageChangeListener {
    private SkinTabLayout tabLayout;
    private ViewPager viewPager;
    private ArrayList<Pair<String, Fragment>> items;
    private EntrustAdapter entrustAdapter;
    private TopBar topBar;
    private View revokeAllOrders;
    private View filterLayout;
    private boolean isShowFilter = false;
    private EditText baseTokenEt;
    private EditText quoteTokenEt;
    private RadioGroup orderStatusRadio;
    private RadioGroup priceModeRadio;
    private OrderFilterEvent filterEventCurrent = new OrderFilterEvent();
    private OrderFilterEvent filterEventHistory = new OrderFilterEvent();
    //默认是当前委托单列表
    private boolean isOpenOrders=true;
    //当前筛选条件
    private OrderFilterEvent currentFilterEvent;

    @Override
    protected int getContentView() {
        return R.layout.activity_all_orders_layout;
    }

    @Override
    protected AllOrderPresenter createPresenter() {
        return new AllOrderPresenter();
    }

    @Override
    protected AllOrderPresenter.AllOrderUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        filterLayout = viewFinder.find(R.id.filter_layout);
        topBar = viewFinder.find(R.id.topBar);
        // TODO: night-mode未生效
        topBar.setLeftImg(R.mipmap.btn_head_back);
        topBar.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowFilter) {
                    closeKeyBoard();
                    isShowFilter = false;
                    filterLayout.setVisibility(View.GONE);
                    return;
                }
                finish();
            }
        });
        topBar.setRightImg(R.mipmap.icon_book_setting);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isShowFilter) {
                    isShowFilter = true;
                    filterLayout.setVisibility(View.VISIBLE);
                } else {
                    closeKeyBoard();
                    isShowFilter = false;
                    filterLayout.setVisibility(View.GONE);
                }
            }
        });
        tabLayout = viewFinder.find(R.id.tabLayout);
        viewPager = viewFinder.find(R.id.viewPager);
        revokeAllOrders = viewFinder.find(R.id.revoke_all_orders);

        baseTokenEt = viewFinder.editText(R.id.baseToken);
        quoteTokenEt = viewFinder.editText(R.id.quoteToken);

        orderStatusRadio = viewFinder.find(R.id.order_status_group);
        priceModeRadio = viewFinder.find(R.id.price_mode_group);

        currentFilterEvent = filterEventCurrent;
        initTabs();
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.filter_layout).setOnClickListener(this);
        viewFinder.find(R.id.revoke_all_orders).setOnClickListener(this);
        viewFinder.find(R.id.btn_reset).setOnClickListener(this);
        viewFinder.find(R.id.btn_complete).setOnClickListener(this);
        viewPager.addOnPageChangeListener(this);
        orderStatusRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (isOpenOrders) {
                    switch (checkedId) {
                        case R.id.order_status_all:
                            filterEventCurrent.orderStatus = "";
                            break;
                        case R.id.order_status_buy:
                            filterEventCurrent.orderStatus = "BUY";
                            break;
                        case R.id.order_status_sell:
                            filterEventCurrent.orderStatus = "SELL";
                            break;
                    }
                }else{
                    switch (checkedId) {
                        case R.id.order_status_all:
                            filterEventHistory.orderStatus = "";
                            break;
                        case R.id.order_status_buy:
                            filterEventHistory.orderStatus = "BUY";
                            break;
                        case R.id.order_status_sell:
                            filterEventHistory.orderStatus = "SELL";
                            break;
                    }
                }

            }
        });

        priceModeRadio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (isOpenOrders) {
                    switch (checkedId) {
                        case R.id.price_mode_all:
                            filterEventCurrent.priceMode = "";
                            break;
                        case R.id.price_mode_limited:
                            filterEventCurrent.priceMode = "LIMIT";
                            break;
                        case R.id.price_mode_market:
                            filterEventCurrent.priceMode = "MARKET";
                            break;
                    }
                }else{
                    switch (checkedId) {
                        case R.id.price_mode_all:
                            filterEventHistory.priceMode = "";
                            break;
                        case R.id.price_mode_limited:
                            filterEventHistory.priceMode = "LIMIT";
                            break;
                        case R.id.price_mode_market:
                            filterEventHistory.priceMode = "MARKET";
                            break;
                    }
                }

            }
        });
    }

    private void initTabs() {
        items = new ArrayList<>();

        items.add(new Pair<String, Fragment>(getString(R.string.string_current_entrust), new CurrentEntrustOrderFragment()));
        items.add(new Pair<String, Fragment>(getString(R.string.string_history_entrust), new HistoryEntrustOrderFragment()));
        entrustAdapter = new EntrustAdapter(getSupportFragmentManager());
        viewPager.setAdapter(entrustAdapter);
        tabLayout.setupWithViewPager(viewPager);
//        tab.setTabTextColors(getResources().getColor(R.color.color_white),getResources().getColor(R.color.color_black));
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);

//        viewPager.addOnPageChangeListener(this);
        CommonUtil.setUpIndicatorWidthByReflex(tabLayout,15,15);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.revoke_all_orders:
                EventBus.getDefault().post(new RevokeOrderEvent());
                break;

            case R.id.btn_reset:
                baseTokenEt.setText("");
                quoteTokenEt.setText("");
                ((RadioButton) viewFinder.find(R.id.order_status_all)).setChecked(true);
                ((RadioButton) viewFinder.find(R.id.price_mode_all)).setChecked(true);
                resetFilterConditions();
                break;
            case R.id.btn_complete:
                closeKeyBoard();
                String baseToken = viewFinder.editText(R.id.baseToken).getText().toString().trim();
                String quoteToken = viewFinder.editText(R.id.quoteToken).getText().toString().trim();
                if (isOpenOrders) {
                    filterEventCurrent.baseToken = baseToken;
                    filterEventCurrent.quoteToken = quoteToken;
                }else{
                    filterEventHistory.baseToken = baseToken;
                    filterEventHistory.quoteToken = quoteToken;
                }
                EventBus.getDefault().post(currentFilterEvent);
                isShowFilter = false;
                filterLayout.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 重置当前tab订单的过滤条件
     */
    private void resetFilterConditions() {
        if (isOpenOrders) {
            filterEventCurrent.baseToken="";
            filterEventCurrent.quoteToken="";
            filterEventCurrent.orderStatus="";
            filterEventCurrent.priceMode="";
        }else{
            filterEventHistory.baseToken="";
            filterEventHistory.quoteToken="";
            filterEventHistory.orderStatus="";
            filterEventHistory.priceMode="";
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            closeKeyBoard();
            if (isShowFilter) {
                isShowFilter = false;
                filterLayout.setVisibility(View.GONE);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void closeKeyBoard() {
        KeyBoardUtil.closeKeybord(viewFinder.textView(R.id.baseToken),AllOrdersActivity.this);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position == 0) {
            isOpenOrders = true;
            currentFilterEvent = filterEventCurrent;
            revokeAllOrders.setVisibility(View.VISIBLE);
        } else {
            isOpenOrders = false;
            currentFilterEvent = filterEventHistory;
            revokeAllOrders.setVisibility(View.GONE);
        }
        setFilterView();
    }

    private void setFilterView() {
        baseTokenEt.setText(currentFilterEvent.baseToken);
        quoteTokenEt.setText(currentFilterEvent.quoteToken);
        if (TextUtils.isEmpty(currentFilterEvent.orderStatus)) {
            orderStatusRadio.check(R.id.order_status_all);
        }else if(currentFilterEvent.orderStatus.equalsIgnoreCase("BUY")){
            orderStatusRadio.check(R.id.order_status_buy);
        }else if(currentFilterEvent.orderStatus.equalsIgnoreCase("SELL")){
            orderStatusRadio.check(R.id.order_status_sell);
        }
        if (TextUtils.isEmpty(currentFilterEvent.priceMode)) {
            priceModeRadio.check(R.id.price_mode_all);
        }else if(currentFilterEvent.priceMode.equalsIgnoreCase("LIMIT")){
            priceModeRadio.check(R.id.price_mode_limited);
        }else if(currentFilterEvent.priceMode.equalsIgnoreCase("MARKET")){
            priceModeRadio.check(R.id.price_mode_market);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private class EntrustAdapter extends FragmentPagerAdapter {

        public EntrustAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return items.get(position).second;
        }

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return items.get(position).first;
        }

    }
}
